/**
 * kaGrid 封装
 * 
 * 版本：v1.0
 * 
 * Stanley
 **/
layui.define(['jquery', 'table', 'kaMsg', 'kaGridCols', 'kaGridData', 'kaGridListHeaderMenu', 'kaGridEndButton', 'kaGridTopButton', 'kaGridHeaders', 'kaGridWhere'],
    function (exports) {
        var $ = layui.jquery;
        var table = layui.table;
        var kaGridCols = layui.kaGridCols;
        var kaGridData = layui.kaGridData;
        var kaGrid = new function () {
            // 初始化
            this.init = function (params) {
                if (params.colsBoolean == undefined) {
                    if (params.cols != undefined && params.cols != null) {
                        params["colsBoolean"] = 3; // 初始化
                    } else {
                        params["colsBoolean"] = 1; // 初始化
                    }
                }
                // 获取列表头
                params.cols = kaGridCols.get(params);
                // 获取数据
                if (params.dataBoolean == undefined) {
                    params["dataBoolean"] = 1; // 初始化
                }
                // 获取Where
                if (params.whereBoolean == undefined) {
                    params["whereBoolean"] = 1; // 初始化
                }
                // 获取header
                if (params.headerBoolean == undefined) {
                    params["headerBoolean"] = 1; // 初始化
                }
                return this.render(params);
            }
            // 渲染Grid
            this.render = function (params) {
                var autoSortBoolean = false;
                // 判断ID
                if (params.id == undefined) { params.id = "kaDataGridId"; }
                // 装载配置
                if (top.kaGridAllParams == undefined || top.kaGridAllParams == null) { top.kaGridAllParams = {}; }
                top.kaGridAllParams["table_Params_" + params.id] = params;
                // 获取数据
                if ((params.url == undefined || params.url == null) && params.data != undefined && params.data != null) {
                    if (params.dataBoolean == 1 || params.dataBoolean == undefined) {
                        params["dataBoolean"] = 3; // 初始化
                    }
                    params["data"] = kaGridData.get(params);
                    autoSortBoolean = true;
                } else {
                    if (params.url != undefined && params.url != null) {
                        var kaBgUrl = layui.kaBgUrl.url(params.url);
                        if (kaBgUrl != undefined && kaBgUrl != null && kaBgUrl != "") {
                            kaBgUrl = layui.kaBgUrl.url(params.url).url;
                        } else {
                            kaBgUrl = params.url;
                        }
                        params.url = kaBgUrl;
                        if (params.method == undefined || params.method == null) {
                            params["method"] = "GET";
                        }
                        if (params.contentType == undefined || params.contentType == null) {
                            params["contentType"] = "application/json";
                        }
                        if (params.dataType == undefined || params.dataType == null) {
                            params["dataType"] = "json";
                        }
                        params["request"] = {
                            "pageName": 'pageNum',
                            "limitName": 'pageSize',
                        }
                        params["parseData"] = function (res) { // res 即为原始返回的数据
                            return {
                                "code": res.code == 200 ? "0" : res.code, // 解析接口状态
                                "msg": res.msg, // 解析提示文本
                                "count": res.total, // 解析数据长度
                                "data": res.data  // 解析数据列表
                            };
                        }
                        params["ajax"] = function (origOptions, type) {
                            //临时解决layuiTable 传入的data 不删除的情况
                            var dataJson = JSON.parse(origOptions.data);
                            var field = layui.form.val(params.id + "_filter");
                            field["pageNum"] = dataJson["pageNum"];
                            field["pageSize"] = dataJson["pageSize"];
                            origOptions.data = JSON.stringify(field);
                            // -------
                            var paramsx = top.kaGridAllParams["table_Params_" + params.id];
                            var dataBooleanBs = paramsx.dataBoolean;
                            paramsx.dataBoolean = 1;
                            kaGridData.get(paramsx, undefined, origOptions, type, dataBooleanBs);
                        }
                    }
                }
                // 获取头部
                // params["headers"] = layui.kaGridHeaders.get(params);
                // 获取where
                params["where"] = layui.kaGridWhere.get(params);
                // 加载Loading
                params["loading"] = '<i class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"></i>'
                // 高度计算
                var height = 'full-1';
                if (params.height != undefined && params.height != null && params.height != "") {
                    height = params.height;
                }
                // 上传按钮
                var uploadButton = undefined;
                if (params.importtemplateurl != undefined && params.importtemplateurl != null && params.importtemplateurl != "") {
                    uploadButton = { // 右上角工具图标
                        title: '导入',
                        layEvent: 'LAYTABLE_UPLOAD',
                        icon: 'layui-icon-upload-drag',
                        importtemplateurl: params.importtemplateurl,
                        importurl: params.importurl,
                        onClick: function (obj) { // 2.9.12+
                            // 当前示例配置项
                            var options = obj.config;
                            var optionsParams = options.params;
                            // 弹出面板
                            obj.openPanel({
                                list: [ // 列表
                                    `<li data-type="uploadTemplate">
                                        <div  style="height: 100px;border: 2px solid #0059f554;text-align: center;padding-top: 15px;">
                                            <i class="icon Kaultraiconfont Kaultraicon-shujutongburizhi" style="color: red;font-size: 35px;"></i>
                                            <div style="color: var(--global-primary-color);font-weight: 900;">点击模板下载</div>
                                        </div>
                                    </li>`,
                                    `<li data-type="uploadData"  data-importtemplateurl="` + optionsParams.importtemplateurl + `"  data-importurl="` + optionsParams.importurl + `" style="text-align: center;color: #00390a;font-weight: bold;font-size: 15px;padding-top: 6px;">
                                        <span>【</span><span>点击导入</span><span>】</span>
                                     </li>`
                                ].join(''),
                                done: function (panel, list) { // 操作列表
                                    list.on('click', function () {
                                        var type = $(this).data('type');
                                        var importtemplateurl = $(this).data('importtemplateurl');
                                        var importurl = $(this).data('importurl');
                                        if (type === 'uploadTemplate') {
                                            window.open(importtemplateurl);
                                        } else if (type === 'uploadData') {
                                            var myopt = {
                                                title: "数据导入",
                                                synopsis: "请下载“导入模板”，填入数据，并上传文件。",
                                                accept: "file",
                                                size: 1000,
                                                url: importurl,
                                                mb: {
                                                    title: "导入模板",
                                                    url: importtemplateurl
                                                },
                                                cb: function (res) {
                                                    layui.kaGridSearch.init('kaDataGridId');
                                                }
                                            };
                                            layui.kaFile.open(myopt);

                                        }
                                    });
                                }
                            });
                        }
                    };
                }
                // 更多应用
                var gdAppButtons = undefined;
                if (params.importtemplateurl != undefined && params.importtemplateurl != null && params.importtemplateurl != "") {
                    gdAppButtons = { // 右上角工具图标
                        title: '更多应用',
                        layEvent: 'LAYTABLE_TABLE_APP',
                        icon: 'layui-icon-app',
                        onClick: function (obj) { // 2.9.12+
                            layer.open({
                                id: "LAYTABLETABLEAPPHTML",
                                type: 1,
                                title: '更多应用',
                                shadeClose: true,
                                shade: [0.6, '#FFF'],
                                area: ['680px', '480px'],
                                content: `
                                    <div style="padding: 32px;">
                                        <div class="layui-row layui-col-space5">
                                            <div class="layui-col-xs3">
                                                <button onclick="layui.kaPublic.kaMySmallToolOpenView('2', '计算器', './view/myTool/calculator/index.html', '386px','572px', 0)" style="width: 100%;height: 120px;" class="layui-btn layui-btn-primary layui-border-blue">
                                                    <i class="icon Kaultraiconfont Kaultraicon-jisuanqilishuai" style="font-size: 36px;"></i>
                                                    <div>计算器</div>
                                                </button>
                                            </div>
                                            <div class="layui-col-xs3">
                                                <button onclick="layui.kaPublic.kaMySmallToolOpenView('2', '图表生成', './view/myTool/calculator/index.html', '386px','572px', 0)" style="width: 100%;height: 120px;" class="layui-btn layui-btn-primary layui-border-blue">
                                                    <i class="icon Kaultraiconfont Kaultraicon-tubiao" style="font-size: 36px;"></i>
                                                    <div>图表生成 </div>
                                                </button>
                                            </div>
                                        </div>
                                    </div>` // iframe 的 url
                            });
                        }
                    }
                }
                // 默认顶部按钮
                var defaultToolbar = ['filter', {
                    name: 'exports',
                    onClick: function (obj) {
                        // 获得数据并清除临时字段
                        var data = table.clearCacheKey(obj.data);
                        // 当前示例配置项
                        var options = obj.config;
                        var optionsParams = options.params;
                        // ----- 判断
                        var hdXLSX = "";
                        if (optionsParams.backendexporturl != undefined && optionsParams.backendexporturl != null && optionsParams.backendexporturl != "") {
                            hdXLSX = `<li data-backendexporturl="` + optionsParams.backendexporturl + `" data-type="xlsxHD">
                                             <i class="icon Kaultraiconfont Kaultraicon-shujutongburizhi" style="color: red;"></i> 导出 XLSX 文件（后端）
                                          </li>`;
                        }
                        // 弹出面板
                        obj.openPanel({
                            list: [ // 列表
                                `<li data-type="csv">
                                        <i class="icon Kaultraiconfont Kaultraicon-daochuwenjian" style="color: var(--global-primary-color);"></i> 导出 CSV 文件（前端）
                                    </li>`,
                                `<li data-type="xlsx">
                                       <i class="icon Kaultraiconfont Kaultraicon-daochuwenjian" style="color: #009120;"></i> 导出 XLSX 文件（前端）
                                    </li>`,
                                hdXLSX
                            ].join(''),
                            done: function (panel, list) { // 操作列表
                                list.on('click', function () {
                                    var type = $(this).data('type')
                                    var backendexporturl = $(this).data('backendexporturl')
                                    if (type === 'csv') {
                                        // 调用内置导出方法
                                        table.exportFile(options.id, null, type);
                                    } else if (type === 'xlsx') {
                                        table.exportFile(options.id, null, 'xls');
                                    } else if (type === 'xlsxHD') {
                                        layui.kaAjax.ajax(layui.kaBgUrl.url(backendexporturl), function (rs) {
                                            if (rs.code == 200) {
                                                layui.kaMsg.success("导出成功", "1");
                                            }
                                        }, {});
                                    }
                                });
                            }
                        });
                    }
                }, 'print'];
                if (uploadButton != undefined) {
                    defaultToolbar.push(uploadButton);
                }
                if (gdAppButtons != undefined) {
                    defaultToolbar.push(gdAppButtons);
                }
                // 初始化配置
                var gridConfig = {
                    elem: "#" + params.id,
                    defaultToolbar: defaultToolbar,
                    autoSort: autoSortBoolean,
                    height: height,
                    css: ['.layui-table-page { text-align: right; }'].join(''),
                    page: false, // 是否显示分页
                    loadLayer: 0
                }
                // 头部
                if (layui.kaGridTopButton.judge(params)) { // 判断
                    gridConfig["toolbar"] = layui.kaGridTopButton.init(params); // 初始化
                }
                // 底部
                if (layui.kaGridTopButton.judge(params)) { // 判断
                    gridConfig["pagebar"] = layui.kaGridEndButton.init(params); // 初始化
                }
                // 合并配置
                gridConfig = $.extend(gridConfig, params);
                // 加载样式
                gridConfig.size = (gridConfig.size == undefined || gridConfig.size == null || gridConfig.size == "") ? "sm" : gridConfig.size;
                // 加载分页
                if (gridConfig.page) {
                    if (gridConfig.limits == undefined || gridConfig.limits == null) {
                        gridConfig.limits = [10, 25, 50, 100, 200, 500, 1000]
                    }
                    if (gridConfig.limit == undefined || gridConfig.limit == null) {
                        gridConfig.limit = 10;
                    }
                }
                gridConfig.params = params;
                gridConfig.before = function (options) {
                    var loadLayerIndex = layui.kaMsg.loading();
                    this.loadLayer = loadLayerIndex;
                    typeof gridConfig.params.before == "function" && gridConfig.params.before(options);
                }
                // 加载完成后事件
                gridConfig.done = function (res, curr, count, origin) {
                    var loadLayerIndex = this.loadLayer;
                    if (loadLayerIndex > 0) {
                        layui.kaMsg.close(loadLayerIndex);
                    }
                    if (res.code == 0 || res.code == "0") {
                        if (res.data == undefined || res.data.lenght == 0) {
                            $('div[lay-table-id="kaDataGridId"]').each(function () {
                                $(this).find('div[class="layui-none"]').html(`
                                <div style="background-image: url('../admin/images/no_data.png');background-repeat: no-repeat;height: 100px;background-size: contain;width: 130px;margin: 0 auto;margin-top: -30px;">
                                    <div style="margin-top: 90px;font-size: 15px;letter-spacing: 3px;">
                                        无数据
                                    </div>
                                </div>`);
                            })
                        }
                        // 头部工具
                        layui.kaGridListHeaderMenu.init(this);
                        layui.kaGridColsTemplet.loadButtonClick(this.buttonFunUrl);
                        layui.kaGridColsTempletLoadJs.init(this.buttonFunUrl);
                        // 默认工具增加样式
                        layui.table.on('toolbar(kaDataGridId)', function (obj) {
                            var config = obj.config;
                            var btnElem = $(this);
                            var tableId = config.id;
                            var tableView = config.elem.next();
                            // obj.config.bodyUrlId
                            if (obj.event == 'LAYTABLE_COLS') {
                                layui.$('div[lay-event="LAYTABLE_COLS"]').find(".layui-table-tool-panel").each(function () {
                                    var $ = layui.$;
                                    $(this).find("li").each(function () {
                                        $(this).prepend(`<ka class="icon Kaultraiconfont Kaultraicon-tuodong" style="float: left;"></ka>`);
                                    });
                                    //  style="font-size: 12px;"
                                    $(this).addClass("layui-form");
                                    $(this).attr("lay-filter", "LAYTABLE_COLS_filter_form");
                                    $(this).append(`<li><button onclick="layui.kaGridListHeaderMenu.LAYTABLECOLSFilterForm('LAYTABLE_COLS_filter_form','` + config.bodyUrlId + `')" type="button" class="layui-btn layui-btn-sm" style="width: 100%;"><bs style="font-size: 12px;" class="icon Kaultraiconfont Kaultraicon-duigou"></bs>保存</button></li>`);
                                    var that = this;
                                    $(this).sortable({
                                        handle: "ka",
                                        sortableThis: that,
                                        revert: true,
                                        axis: "y",
                                        cursor: "move"
                                    });
                                });
                            }
                        });
                    } else {
                        $('div[lay-table-id="kaDataGridId"]').each(function () {
                            $(this).find('div[class="layui-none"]').html(`
                            <div style="background-image: url('../admin/images/no_data.png');background-repeat: no-repeat;height: 100px;background-size: contain;width: 130px;margin: 0 auto;margin-top: -30px;">
                                <div style="margin-top: 90px;font-size: 15px;letter-spacing: 3px;">
                                ` + res.msg + `
                                </div>
                            </div>`);
                        })
                    }
                    // 头部工具
                    layui.kaGridListHeaderMenu.init(this);
                    layui.kaGridColsTemplet.loadButtonClick(this.buttonFunUrl);
                    layui.kaGridColsTempletLoadJs.init(this.buttonFunUrl);

                    var fieldValues = layui.form.val(this.id + "_filter");
                    layui.$(".kaGridTopFindQueryJudge").find("select").each(function () {
                        var layFilter = layui.$(this).attr("lay-filter");
                        var fv = fieldValues[layFilter];
                        var fvKaJudge = layFilter.split("KaJudge");
                        layui.kaGridTopButton.findQueryInput(fv, fvKaJudge[0]);
                        //监听select
                        layui.form.on('select(' + layFilter + ')', function (data) {
                            var elem = data.elem; // 获得 select 原始 DOM 对象 _value
                            var KaJudge = layui.$(elem).attr("lay-filter").split("KaJudge");
                            var value = data.value; // 获得被选中的值
                            layui.$("#" + KaJudge[0] + "_value").val("");
                            layui.kaGridTopButton.findQueryInput(value, KaJudge[0]);
                        });
                    });
                    // layui.kaGridTopButton.queryListShowHidenStart('kaDataGridId', '2', 1);
                    console.log(res); // 得到当前渲染的数据
                    console.log(curr);  // 得到当前页码
                    console.log(count); // 得到数据总量
                    console.log(origin); // 回调函数所执行的来源 --- 2.8.7+
                }
                // 数据接口请求完成后执行，无论成功还是失败均会触发
                gridConfig.complete = function (xhr, ts) {
                    var loadLayerIndex = this.loadLayer;
                    if (loadLayerIndex > 0) {
                        layui.kaMsg.close(loadLayerIndex);
                    }
                }
                // 渲染Grid
                return table.render(gridConfig);
            }
            // 解析
            this.getKaGridParams = function (data) {
                var params = {};
                params["tableId"] = data.id;
                if (data.colsBoolean != undefined && data.colsBoolean != null && data.colsBoolean != "") {
                    params["colsBoolean"] = data.colsBoolean;
                }
                if (data.height != undefined && data.height != null && data.height != "") {
                    params["height"] = data.height;
                }
                if (data.bodyUrlId != undefined && data.bodyUrlId != null && data.bodyUrlId != "") {
                    params["bodyUrlId"] = data.bodyUrlId;
                }
                if (data.cols != undefined && data.cols != null && data.cols != "") {
                    if (data.colsBoolean == 3) {
                        params["cols"] = JSON.parse(data.cols);
                    } else if (data.colsBoolean == 1) {
                        params["cols"] = data.cols;
                    }
                } else if (data.colsBoolean == 1) {
                    params["cols"] = data.cols;
                }
                if (data.url != undefined && data.url != null && data.url != "") {
                    params["url"] = data.url;
                }
                if (params.method != undefined && params.method != null && params.method != "") {
                    params["method"] = params.method;
                }
                if (params.contentType != undefined && params.contentType != null && params.contentType != "") {
                    params["contentType"] = params.contentType;
                }
                if (params.dataType != undefined && params.dataType != null && params.dataType != "") {
                    params["dataType"] = params.dataType;
                }
                if (data.dataBoolean != undefined && data.dataBoolean != null && data.dataBoolean != "") {
                    params["dataBoolean"] = data.dataBoolean;
                }
                if (data.data != undefined && data.data != null && data.data != "") {
                    if (data.dataBoolean == 3) {
                        params["data"] = data.data;
                    }
                }
                if (data.page != undefined && data.page != null && data.page != "") {
                    if (data.page == 0) {
                        params["page"] = false;
                    } else if (data.page == 1) {
                        params["page"] = true;
                    }
                }
                if (data.headerBoolean != undefined && data.headerBoolean != null && data.headerBoolean != "") {
                    params["headerBoolean"] = data.headerBoolean;
                }
                if (data.whereBoolean != undefined && data.whereBoolean != null && data.whereBoolean != "") {
                    params["whereBoolean"] = data.whereBoolean;
                }
                if (data.size != undefined && data.size != null && data.size != "") {
                    params["size"] = data.size;
                }
                if (data.limits != undefined && data.limits != null && data.limits != "") {
                    params["limits"] = data.limits;
                }
                if (data.limit != undefined && data.limit != null && data.limit != "") {
                    params["limit"] = data.limit;
                }
                if (data.checkboxBoolean != undefined && data.checkboxBoolean != null && data.checkboxBoolean != "") {
                    params["checkboxBoolean"] = data.checkboxBoolean;
                }
                if (data.buttonFunUrl != undefined && data.buttonFunUrl != null && data.buttonFunUrl != "") {
                    params["buttonFunUrl"] = data.buttonFunUrl;
                }
                if (data.height != undefined && data.height != null && data.height != "") {
                    params["height"] = data.height;
                }
                if (data.myToolbar != undefined && data.myToolbar != null && data.myToolbar != "") {
                    params["myToolbar"] = data.myToolbar;
                }
                if (data.where != undefined && data.where != null && data.where != "") {
                    params["where"] = data.where;
                }
                if (data.backendexporturl != undefined && data.backendexporturl != null && data.backendexporturl != "") {
                    params["backendexporturl"] = data.backendexporturl;
                }
                if (data.importtemplateurl != undefined && data.importtemplateurl != null && data.importtemplateurl != "") {
                    params["importtemplateurl"] = data.importtemplateurl;
                }
                if (data.importurl != undefined && data.importurl != null && data.importurl != "") {
                    params["importurl"] = data.importurl;
                }
                return params;
            }
        };
        exports('kaGrid', kaGrid);
    }
)